package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.R;
import com.itheima.dao.ShoppingCartDao;
import com.itheima.entity.ShoppingCart;
import com.itheima.service.ShoppingCartService;
import com.itheima.utils.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author Tang
 * @date 2023/4/17
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartDao, ShoppingCart> implements ShoppingCartService {

    @Autowired
    ShoppingCartService shoppingCartService;
    /**
     * 添加购物车
     * @param shoppingCart
     */
    @Override
    public void add(ShoppingCart shoppingCart) {
        //0.获取当前登录的用户id
        Long userId = BaseContext.getValue();

        //1.补齐字段user_id、number、create_time
        shoppingCart.setUserId(userId);
        shoppingCart.setCreateTime(LocalDateTime.now());

        //1.1 情况一：购物车中不存在该商品，数量给1
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        if (shoppingCart.getDishId() != null) { //如果添加的是菜品，那就根据菜品id查
            wrapper.eq(ShoppingCart::getDishId, shoppingCart.getDishId());
            wrapper.eq(shoppingCart.getDishFlavor()!=null, ShoppingCart::getDishFlavor, shoppingCart.getDishFlavor());
        }else { //添加套餐
            wrapper.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }
        ShoppingCart cart = this.getOne(wrapper);
        /*if (cart == null) {
            shoppingCart.setNumber(1);
            this.save(shoppingCart);
        }else {
            //1.2 情况二：购物车中已存在该商品，数量应该＋1
            cart.setNumber(cart.getNumber() + 1);
            //2.调用自身的更新方法，保存数据到购物车
            this.updateById(cart);
        }*/
        if (cart != null) {
            //情况二：购物车中已存在该商品，数量应该＋1
            cart .setNumber(cart.getNumber() + 1);
        } else {
            //情况一：购物车中不存在该商品，数量给1
            cart = shoppingCart;
            cart.setNumber(1);
        }
        //2.调用新增或更新方法
        this.saveOrUpdate(cart);
    }

    //清空购物车
    @Override
    public R clean() {

        Long userId = BaseContext.getValue();
        //2.调用service根据当前登录的用户id完成删除当前用户购物车中所有数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,userId);
        boolean remove = shoppingCartService.remove(wrapper);
        //3.返回处理结果
        return remove?R.success("清空购物车成功"):R.error("清空购物车失败");
    }
}
